package org.kl.wx.service;

import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.kl.bf.web.base.BasicController;
import org.kl.wx.entity.Media;
import org.kl.wx.repository.MediaDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class MediaService {
	private MediaDao mediaDao;

	@Autowired
	public void setMediaDao(MediaDao mediaDao) {
		this.mediaDao = mediaDao;
	}

	public Media getMedia(String id) {
		return mediaDao.find(Media.class, id);
	}

	public void saveMedia(Media entity) {
		mediaDao.save(entity);
	}

	public void deleteMedia(String id) {
		mediaDao.delete(id);
	}

	public List<Media> getAllmedia() {
		return mediaDao.findAll();
	}

	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				mediaDao.delete(id);
				i++;
			}
		}
		return "成功删除" + i + "条记录";
	}
	
	//发送消息保存到本地数据库
	public Media saveMedia(String mediaType,String title,String introduction, File file){
		
		Media media = new Media();
		media.setMediaType(mediaType);
		media.setFileName(file.getName());
		media.setFilePath(file.getPath());
		media.setFileSize(file.length()/1024.0);
		media.setIntroduction(introduction);
		media.setTitle(title);
		media.setUploader(BasicController.getCurrentUserName());
		media.setUploadTime(new Timestamp(new Date().getTime()));
		mediaDao.save(media);
		return media;
	}

	/**
	 * 按条件查询
	 */
	public List<Media> getMedia(Map<String, Object> searchParams) {
		Specification<Media> spec = buildSpecification(searchParams);
		return mediaDao.findAll(spec);
	}

	/**
	 * 按条件分页查询
	 */
	public Page<Media> getMedia(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<Media> spec = buildSpecification(searchParams);

		return mediaDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Media> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<Media> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), Media.class);
		return spec;
	}

}
